#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main(){
    int server_id,new_socket;
    struct sockaddr_in address;
    int opt=1;
    int addrlen=sizeof(address);
    char buffer[BUFFER_SIZE]={0};
    const char *hello="Hello from server";
    //创建socket
    if((server_id=socket(AF_INET, SOCK_STREAM, 0))==0){
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    //绑定地址端口
    if(setsockopt(server_id, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))){
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    address.sin_family=AF_INET;
    address.sin_addr.s_addr=INADDR_ANY;
    address.sin_port=htons(PORT);

    if(bind(server_id,(struct sockaddr *)&address, sizeof(address))<0){
        perror("bind failed");
        close(server_id);
        exit(EXIT_FAILURE);
    }

    //监听
    if(listen(server_id, 3)<0){
        perror("listen");
        close(server_id);
        exit(EXIT_FAILURE);
    }
    //接受连接
    if((new_socket=accept(server_id, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0){
        perror("accept");
        close(server_id);
        exit(EXIT_FAILURE);
    }
    //读取客户端发送的数据
    read(new_socket, buffer, BUFFER_SIZE);
    printf("客户端发送的数据:%s\n", buffer);
    //向客户端发送数据
    send(new_socket, hello, strlen(hello), 0);
    printf("Hello message sent\n");
    close(new_socket);
    close(server_id);
    return 0;
}